import base64
import os
import re

from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.models import OAuthQQUser
from oauth.utils import OAuthQQ
from users.models import User


class OAuthQQUserSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    access_token = serializers.CharField(label='加密openid', write_only=True)
    token = serializers.CharField(max_length=64, label='jwt token', read_only=True)

    class Meta:
        model = User
        fields = ('id', 'mobile', 'password', 'username', 'sms_code', 'access_token', 'token')
        extra_kwargs = {
            'mobile': {
                'write_only': True
            },
            'password': {
                'write_only': True
            },
            'username': {
                'read_only': True
            }
        }

    # 数据校验，参数完整性，手机号格式，短信验证码是否正确，access_token是否有效
    def validate_mobile(self, value):
        if not re.match(r'1[3-9]\d{9}', value):
            raise serializers.ValidationError('手机号格式不正确')
        return value

    def validate(self, attrs):

        # access_token是否有效
        access_token = attrs['access_token']

        # 借助OAuthQQ类中的方法对access_token进行解密
        openid = OAuthQQ.check_save_user_token(access_token)

        # 解密失败会返回None
        if openid is None:
            raise serializers.ValidationError('OpenID解密失败')

        attrs['openid'] = openid

        # 短信验证码是否正确
        mobile = attrs['mobile']
        sms_code = attrs['sms_code']

        # 从redis中获取真实的短信验证码
        redis_conn = get_redis_connection('verify_codes')

        # 从redis中取出真实的短信验证码
        real_sms_code = redis_conn.get('sms_%s' % mobile)

        # 判断验证码是否过期
        if real_sms_code is None:
            raise serializers.ValidationError('短信验证码已过期')

        # 判断断验证码是否正确
        if real_sms_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码输入有误')

        # 判断手机号是否已注册，已注册检验密码，未注册则注册新用户
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 未注册则注册新用户
            user = None
        else:
            # 已注册校验密码
            password = attrs['password']

            if not user.check_password(password):
                raise serializers.ValidationError('密码输入错误')

        attrs['user'] = user

        return attrs

    def create(self, validated_data):
        # 如果用户未创建，先创建一个用户
        user = validated_data['user']
        if user is None:
            mobile = validated_data['mobile']
            password = validated_data['password']

            # 随机生成用户名
            username = base64.b64encode(os.urandom(9)).decode()

            # 创建user对象
            user = User.objects.create_user(username=username, password=password, mobile=mobile)

        # 保存QQ绑定的数据
        openid = validated_data['openid']
        OAuthQQUser.objects.create(
            user=user,
            openid=openid
        )

        # 生成jwt token，保存用户身份信息
        from rest_framework_jwt.settings import api_settings

        # 生成payload的方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 生成jwt token的方法
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 生成payload
        payload = jwt_payload_handler(user)
        # 生成jwt token
        token = jwt_encode_handler(payload)

        user.token = token

        return user